package com.mmg.spzx.manager.service.impl;

import com.mmg.spzx.manager.mapper.SysMenuMapper;
import com.mmg.spzx.manager.mapper.SysRoleMenuMapper;
import com.mmg.spzx.manager.service.SysMenuService;
import com.mmg.spzx.manager.utils.MenuHelper;
import com.mmg.spzx.model.entity.system.SysMenu;
import com.mmg.spzx.model.vo.system.SysMenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.LinkedList;
import java.util.List;

@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    public List<SysMenu> findNodes() {
        //查询所有菜单
        List<SysMenu> sysMenuList = sysMenuMapper.findAll();
        //调用工具类的方法，将查询出来的菜单集合转换成树形结构
        return MenuHelper.buildTree(sysMenuList);
    }

    @Override
    public void save(SysMenu sysMenu) {
        sysMenuMapper.save(sysMenu);
        this.updateSysRoleMenuIsHalf(sysMenu);
    }

    private void updateSysRoleMenuIsHalf(SysMenu sysMenu) {
        // 查询是否存在父节点
        SysMenu parentMenu = sysMenuMapper.findById(sysMenu.getParentId());
        if(parentMenu != null) {
            // 将该id的菜单设置为半开
            sysRoleMenuMapper.updateSysRoleMenuIsHalf(parentMenu.getId()) ;
            // 递归调用
            updateSysRoleMenuIsHalf(parentMenu) ;
        }
    }

    @Override
    public void update(SysMenu sysMenu) {
        sysMenuMapper.update(sysMenu);
    }

    @Override
    public void removeById(Integer id) {
        //查询当前菜单是否有子菜单
        int count = sysMenuMapper.countByParentId(id);
        if (count > 0) {
            throw new RuntimeException("当前菜单有子菜单，不能删除");
        }
        //删除当前菜单
        sysMenuMapper.removeById(id);
    }

    @Override
    public List<SysMenuVo> findMenusByUserId(Long id) {
        //查询当前用户可以操作的菜单
        List<SysMenu> sysMenuList = sysMenuMapper.findMenusByUserId(id);
        //将菜单集合转换成树形结构
        return this.buildMenus(MenuHelper.buildTree(sysMenuList));
    }

    // 将List<SysMenu>对象转换成List<SysMenuVo>对象
    private List<SysMenuVo> buildMenus(List<SysMenu> menus) {
        List<SysMenuVo> sysMenuVoList = new LinkedList<SysMenuVo>();
        for (SysMenu sysMenu : menus) {
            SysMenuVo sysMenuVo = new SysMenuVo();
            sysMenuVo.setTitle(sysMenu.getTitle());
            sysMenuVo.setName(sysMenu.getComponent());
            List<SysMenu> children = sysMenu.getChildren();
            if (!CollectionUtils.isEmpty(children)) {
                sysMenuVo.setChildren(buildMenus(children));
            }
            sysMenuVoList.add(sysMenuVo);
        }
        return sysMenuVoList;
    }
}
